<template>
  <div class="student-appointment-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>学员预约管理</span>
          <el-button type="primary" @click="handleAdd">新增预约</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
       
        <el-form-item label="教练姓名">
          <el-input v-model="searchForm.coachName" placeholder="请输入教练姓名" clearable />
        </el-form-item>
       
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="studentName" label="学员姓名" />
        <el-table-column prop="coachName" label="教练姓名" />
        <el-table-column prop="appointmentDate" label="预约日期" />
        <el-table-column prop="timeSlot" label="预约时间">
          <template #default="{ row }">
            {{ timeSlotMap[row.timeSlot] }}
          </template>
        </el-table-column>
        <el-table-column prop="plateNo" label="车牌号" />
       
     
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 教练列表弹窗 -->
    <el-dialog
      v-model="coachDialogVisible"
      title="选择教练"
      width="800px"
    >
      <el-table :data="coachOptions" border style="width: 100%">
        <el-table-column prop="realName" label="教练姓名" />
        <el-table-column prop="carType" label="车型" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="primary" @click="handleSelectCoach(row)">
              预约
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 时间段选择弹窗 -->
    <el-dialog
      v-model="timeSlotDialogVisible"
      :title="`预约教练：${selectedCoach?.realName}`"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="预约日期" prop="appointmentDate">
        
          <el-date-picker
            v-model="form.appointmentDate"
            type="date"
            placeholder="选择日期"
            :disabled-date="disabledDate"
            value-format= "YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item label="车辆" prop="vehicleId">
          <el-select v-model="form.vehicleId" placeholder="请选择车辆" filterable>
            <el-option
              v-for="item in vehicleOptions"
              :key="item.id"
              :label="item.plateNo"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间段" prop="timeSlot">
          <div class="time-slots">
            <el-button
              v-for="slot in timeSlots"
              :key="slot.id"
              :type="form.timeSlot === slot.id ? 'primary' : 'default'"
              :disabled="slot.disabled"
              @click="handleSelectTimeSlot(slot)"
            >
              {{ slot.start }}-{{ slot.end }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="timeSlotDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAppointmentList,
  createAppointment,
  updateAppointmentStatus,
  getStudentList,
  getCoachList
} from '@/api/appointment'

import {
 
  getVehicleList
} from '@/api/vehicle'

// 搜索表单
const searchForm = reactive({
  studentName: '',
  coachName: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 教练列表弹窗
const coachDialogVisible = ref(false)
const timeSlotDialogVisible = ref(false)
const selectedCoach = ref(null)
const formRef = ref(null)
const timeSlots = ref([
  { id: 1, start: '08:00', end: '10:00', disabled: false },
  { id: 2, start: '10:00', end: '12:00', disabled: false },
  { id: 3, start: '14:00', end: '16:00', disabled: false },
  { id: 4, start: '16:00', end: '18:00', disabled: false }
])

// 选项数据
const studentOptions = ref([])
const coachOptions = ref([])
const vehicleOptions = ref([])

// 预约表单
const form = reactive({
  studentId: '',
  coachId: '',
  appointmentDate: new Date(),
  timeSlot: '',
  vehicleId: '',  // 改为车辆ID
  status: '0' // 待确认
})

// 表单验证规则
const rules = {
  studentId: [
    { required: true, message: '请选择学员', trigger: 'change' }
  ],
  appointmentDate: [
    { required: true, message: '请选择预约日期', trigger: 'change' }
  ],
  timeSlot: [
    { required: true, message: '请选择时间段', trigger: 'change' }
  ],
  vehicleId: [
    { required: true, message: '请选择车辆', trigger: 'change' }
  ]
}

// 车辆类型选项
const carTypeOptions = [
  { value: '1', label: '小型汽车' },
  { value: '2', label: '大型汽车' },
  { value: '3', label: '摩托车' }
]

// 时间段映射
const timeSlotMap = {
  1: '08:00-10:00',
  2: '10:00-12:00',
  3: '14:00-16:00',
  4: '16:00-18:00'
}

// 获取预约列表
const fetchAppointmentList = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm
    }
    const res = await getAppointmentList(params)
    tableData.value = res.records
    total.value = res.total
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败')
  }
}

// 获取学员和教练选项
const fetchOptions = async () => {
  try {
    // 获取学员列表
    const studentRes = await getStudentList()
    studentOptions.value = studentRes.data.records

    // 获取教练列表
    const coachRes = await getCoachList()
    coachOptions.value = coachRes.data.records
  } catch (error) {
    console.error('获取选项数据失败:', error)
    ElMessage.error('获取选项数据失败')
  }
}

// 获取车辆列表
const fetchVehicleList = async () => {
  try {
    const res = await getVehicleList()
    vehicleOptions.value = res.records
  } catch (error) {
    console.error('获取车辆列表失败:', error)
    ElMessage.error('获取车辆列表失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchAppointmentList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.studentName = ''
  searchForm.coachName = ''
  searchForm.status = ''
  handleSearch()
}

// 获取教练列表
const fetchCoachList = async () => {
  try {
    const res = await getCoachList()
    coachOptions.value = res.records
  } catch (error) {
    console.error('获取教练列表失败:', error)
    ElMessage.error('获取教练列表失败')
  }
}

// 检查时间段是否可预约
const checkTimeSlotAvailability = async (coachId, date, timeSlot) => {
  try {
    const res = await getAppointmentList({
      coachId,
      appointmentDate: date,
      timeSlot
    })
    return res.total === 0
  } catch (error) {
    console.error('检查时间段失败:', error)
    return false
  }
}

// 打开教练选择弹窗
const handleAdd = async () => {
  await fetchCoachList()
  coachDialogVisible.value = true
}

// 选择教练后打开时间段选择弹窗
const handleSelectCoach = async (coach) => {
  selectedCoach.value = coach
  form.coachId = coach.id
  
  // 检查当天各时间段的可用性
  const date = form.appointmentDate
  for (const slot of timeSlots.value) {
    slot.disabled = !(await checkTimeSlotAvailability(coach.id, date, slot.id))
  }
  
  timeSlotDialogVisible.value = true
}

// 日期变化时重新检查时间段可用性
const handleDateChange = async () => {
  if (!selectedCoach.value) return
  
  const date = form.appointmentDate
  form.appointmentDate = date
  for (const slot of timeSlots.value) {
    slot.disabled = !(await checkTimeSlotAvailability(selectedCoach.value.id, date, slot.id))
  }
}

// 选择时间段
const handleSelectTimeSlot = (slot) => {
  if (slot.disabled) return
  form.timeSlot = slot.id
}

// 提交预约
const handleSubmit = async () => {
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await createAppointment(form)
        ElMessage.success('预约成功')
        timeSlotDialogVisible.value = false
        coachDialogVisible.value = false
        fetchAppointmentList()
      } catch (error) {
        console.error('预约失败:', error)
        ElMessage.error('预约失败')
      }
    }
  })
}

// 确认预约
const handleConfirm = (row) => {
  ElMessageBox.confirm('确认该预约吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await updateAppointmentStatus(row.id, '1')
      ElMessage.success('确认成功')
      fetchAppointmentList()
    } catch (error) {
      console.error('确认预约失败:', error)
      ElMessage.error('确认预约失败')
    }
  }).catch(() => {})
}

// 取消预约
const handleCancel = (row) => {
  ElMessageBox.confirm('确认取消该预约吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await updateAppointmentStatus(row.id, '3')
      ElMessage.success('取消成功')
      fetchAppointmentList()
    } catch (error) {
      console.error('取消预约失败:', error)
      ElMessage.error('取消预约失败')
    }
  }).catch(() => {})
}

// 完成预约
const handleComplete = (row) => {
  ElMessageBox.confirm('确认完成该预约吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await updateAppointmentStatus(row.id, '2')
      ElMessage.success('完成成功')
      fetchAppointmentList()
    } catch (error) {
      console.error('完成预约失败:', error)
      ElMessage.error('完成预约失败')
    }
  }).catch(() => {})
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAppointmentList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAppointmentList()
}

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    '0': 'warning',
    '1': 'primary',
    '2': 'success',
    '3': 'info'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    '0': '待确认',
    '1': '已确认',
    '2': '已完成',
    '3': '已取消'
  }
  return texts[status] || '未知'
}

// 页面加载时获取数据
onMounted(() => {
  fetchAppointmentList()
  fetchVehicleList()
})
</script>

<style scoped>
.student-appointment-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.time-slots {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.time-slots .el-button {
  width: 100%;
}
</style> 